<template>
  <div class="bom-selector">
    <el-dialog
      :title="title"
      v-model="visible"
      width="900px"  
      append-to-body
      @close="handleClose"
      destroy-on-close
    >
      <!-- 搜索条件 -->
      <el-form :model="queryParams" ref="queryRef" :inline="true" label-width="80px">
        <el-form-item label="BOM编号" prop="bomCode">
          <el-input
            v-model="queryParams.bomCode"
            placeholder="请输入BOM编号"
            clearable
            @keyup.enter="handleQuery"
          />
        </el-form-item>
        <el-form-item label="BOM名称" prop="bomName">
          <el-input
            v-model="queryParams.bomName"
            placeholder="请输入BOM名称"
            clearable
            @keyup.enter="handleQuery"
          />
        </el-form-item>
        <el-form-item label="产品" prop="productId">
          <el-select
            v-model="queryParams.productId"
            placeholder="请选择产品"
            clearable
            @keyup.enter="handleQuery"
          >
            <el-option
              v-for="item in productOptions"
              :key="item.productId"
              :label="item.productName"
              :value="item.productId"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="BOM类型" prop="bomType">
          <el-select v-model="queryParams.bomType" placeholder="请选择BOM类型" clearable>
            <el-option
              v-for="dict in bom_type"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-select v-model="queryParams.status" placeholder="请选择状态" clearable>
            <el-option
              v-for="dict in bom_status"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
          <el-button icon="Refresh" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>

      <!-- 表格数据 -->
      <el-table 
        v-loading="loading" 
        :data="bomList" 
        @row-click="handleRowClick"
        highlight-current-row
        :row-class-name="rowClassName"
        height="300px"
        border
      >
        <el-table-column label="BOM ID" align="center" prop="bomId" width="80" />
        <el-table-column label="BOM编号" align="center" prop="bomCode" width="120" />
        <el-table-column label="BOM名称" align="center" prop="bomName" width="150" />
        <el-table-column label="产品" align="center" prop="productName" width="150" />
        <el-table-column label="版本" align="center" prop="version" width="80" />
        <el-table-column label="BOM类型" align="center" prop="bomType" width="100">
          <template #default="scope">
            <dict-tag :options="bom_type" :value="scope.row.bomType"/>
          </template>
        </el-table-column>
        <el-table-column label="状态" align="center" prop="status" width="80">
          <template #default="scope">
            <dict-tag :options="bom_status" :value="scope.row.status"/>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" width="100">
          <template #default="scope">
            <el-button 
              link 
              type="primary" 
              @click.stop="selectBom(scope.row)"
              :disabled="!isBomSelectable(scope.row)"
            >选择</el-button>
          </template>
        </el-table-column>
      </el-table>

      <pagination
        v-show="total>0"
        :total="total"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="getList"
        :pageSizes="[5, 10, 20, 30]"
        :small="true"
      />

      <!-- 选中的BOM明细展示 -->
      <div v-if="selectedBom && bomDetailList.length > 0" class="bom-detail-container">
        <el-divider content-position="center">BOM物料明细</el-divider>
        <el-table 
          :data="bomDetailList" 
          border 
          height="200px"
          :header-cell-style="{background:'#f7f7f7'}"
        >
          <el-table-column label="序号" type="index" width="80" align="center" />
          <el-table-column label="物料编码" prop="materialCode" width="130" align="center" />
          <el-table-column label="物料名称" prop="materialName" width="160" align="center" />
          <el-table-column label="规格型号" prop="specification" width="190" align="center" />
          <el-table-column label="数量" prop="quantity" width="90" align="center" />
          <el-table-column label="单位" prop="unit" width="90" align="center" />
          <el-table-column label="关键物料" prop="isKeyMaterial" width="100" align="center">
            <template #default="scope">
              <el-tag :type="scope.row.isKeyMaterial === '1' ? 'danger' : 'info'">
                {{ scope.row.isKeyMaterial === '1' ? '是' : '否' }}
              </el-tag>
            </template>
          </el-table-column>
        </el-table>
      </div>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="handleClose">取 消</el-button>
          <el-button 
            type="primary" 
            @click="confirmSelection" 
            :disabled="!selectedBom"
          >确 定</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { listBom, getBom, listProduct } from "@/api/pm/bom";
import { getMaterial } from "@/api/mwm/material"; // 添加物料API导入
import { ref, reactive, toRefs, getCurrentInstance, defineProps, defineEmits, watch } from 'vue';

const { proxy } = getCurrentInstance();
const { bom_status, bom_type } = proxy.useDict('bom_status', 'bom_type');

// 定义属性和事件
const props = defineProps({
  title: {
    type: String,
    default: '选择BOM'
  },
  visible: {
    type: Boolean,
    default: false
  }
});

const emit = defineEmits(['update:visible', 'select']);

// 数据部分
const bomList = ref([]);
const productOptions = ref([]);
const loading = ref(false);
const visible = ref(false);
const total = ref(0);
const selectedBom = ref(null);
const selectedRowIndex = ref(null);
const bomDetailList = ref([]);

const data = reactive({
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    bomCode: null,
    bomName: null,
    productId: null,
    bomType: null,
    status: null
  }
});

const { queryParams } = toRefs(data);

// 监听visible变化
watch(() => props.visible, (val) => {
  if (val) {
    // 当弹窗显示时初始化数据
    getList();
    // 获取产品列表
    getProductList();
  }
  visible.value = val;
});

// 监听内部visible变化
watch(() => visible.value, (val) => {
  emit('update:visible', val);
});

// 查询产品列表
function getProductList() {
  listProduct().then(response => {
    productOptions.value = response.data || [];
  });
}

// 查询BOM列表
function getList() {
  loading.value = true;
  listBom(queryParams.value).then(response => {
    bomList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}

// 获取BOM明细
function getBomDetail(bomId) {
  getBom(bomId).then(async response => {
    if (response.data && response.data.bomDetailList) {
      // 临时存储明细
      const details = response.data.bomDetailList;
      
      // 使用Promise.all并行获取所有物料详细信息
      const detailsWithMaterials = await Promise.all(
        details.map(async detail => {
          // 如果缺少物料信息，则获取物料详情
          if (!detail.materialName || !detail.materialCode || !detail.specification) {
            try {
              // 获取物料详情
              const materialRes = await getMaterial(detail.materialId);
              if (materialRes.data) {
                // 合并物料信息
                return {
                  ...detail,
                  materialName: materialRes.data.materialName || detail.materialName,
                  materialCode: materialRes.data.materialCode || detail.materialCode,
                  specification: materialRes.data.specification || detail.specification,
                  unit: materialRes.data.unit || detail.unit
                };
              }
            } catch (err) {
              console.error("获取物料信息失败:", err);
            }
          }
          // 如果已有完整信息或获取失败，则使用原始数据
          return detail;
        })
      );
      
      bomDetailList.value = detailsWithMaterials;
    } else {
      bomDetailList.value = [];
    }
  });
}

// 判断BOM是否可选
function isBomSelectable(bom) {
  // 通常只有正常状态的BOM可选
  return bom.status === '0' || bom.status === 0;
}

// 行样式
function rowClassName({row, rowIndex}) {
  let classNames = '';
  
  // 选中行高亮
  if (selectedRowIndex.value === rowIndex) {
    classNames += 'row-selected ';
  }
  
  // 不可选择的BOM行样式
  if (!isBomSelectable(row)) {
    classNames += 'row-disabled';
  }
  
  return classNames;
}

// 搜索按钮操作
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

// 重置按钮操作
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

// 行点击事件
function handleRowClick(row, column, event) {
  // 只有可选择的BOM才能被选中
  if (isBomSelectable(row)) {
    selectedBom.value = row;
    selectedRowIndex.value = bomList.value.findIndex(item => item.bomId === row.bomId);
    // 获取BOM明细
    getBomDetail(row.bomId);
  } else {
    // 提示用户该BOM不可选择
    proxy.$modal.msgWarning(`该BOM当前不可用，请选择正常状态的BOM`);
  }
}

// 选择BOM
function selectBom(row) {
  if (isBomSelectable(row)) {
    selectedBom.value = row;
    selectedRowIndex.value = bomList.value.findIndex(item => item.bomId === row.bomId);
    // 获取BOM明细
    getBomDetail(row.bomId);
  }
}

// 确认选择
function confirmSelection() {
  if (selectedBom.value) {
    emit('select', {
      bom: selectedBom.value,
      details: bomDetailList.value
    });
    handleClose();
  }
}

// 关闭对话框
function handleClose() {
  emit('update:visible', false);
  selectedBom.value = null;
  selectedRowIndex.value = null;
  bomDetailList.value = [];
}

// 打开方法，由父组件调用
function open() {
  visible.value = true;
  reset();
  getList();
}

// 重置方法
function reset() {
  queryParams.value.bomCode = null;
  queryParams.value.bomName = null;
  queryParams.value.productId = null;
  queryParams.value.bomType = null;
  queryParams.value.status = null;
  queryParams.value.pageNum = 1;
  selectedBom.value = null;
  selectedRowIndex.value = null;
  bomDetailList.value = [];
}

// 对外暴露方法
defineExpose({
  open
});
</script>

<style scoped>
.bom-selector .row-selected {
  background-color: #f0f9eb !important;
}

.bom-selector .row-disabled {
  background-color: #f9f9f9 !important;
  color: #999 !important;
  cursor: not-allowed !important;
}

.bom-selector .el-table {
  margin-top: 10px;
  margin-bottom: 10px;
}

.bom-selector .pagination-container {
  margin-top: 10px;
}

.bom-detail-container {
  margin-top: 15px;
}
</style> 